<template>
  <el-dialog title="下载" :visible.sync="dialogVisible" width="25%" @close="close">
    <el-table
      :data="urlData"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
      @selection-change="selectionChange"
      ref="downloadTableRef"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column property="title" label="类型" width="150"> </el-table-column>
      <el-table-column label="操作">
        <template v-slot="scoped">
          <el-link type="primary" @click="donwLoadItem(scoped.row)">下载</el-link>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="downLoadSelectSource">下载选择的资源</el-button>
      <el-button type="primary" @click="dialogVisible = false">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import JSZip from 'jszip'
import FileSaver from 'file-saver'

export default {
  name: 'csDownLoadDialog',
  data() {
    return {
      dialogVisible: false,
      urlData: [],
      selectData: [],
      carNumAndTime: ''
    }
  },
  created() {
    this.$bus.$on('sourceDownLoadEvent', (urlData) => {
      this.urlData = urlData
      console.log(this.urlData)
      this.carNumAndTime = `${this.urlData[0].carNum} ${this.urlData[0].time}`
      this.dialogVisible = true
    })
  },
  methods: {
    close() {
      this.$refs.downloadTableRef.clearSelection()
      // this.$bus.$off('sourceDownLoadEvent')
    },
    // 下载单个资源
    donwLoadItem(row) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      console.log(row)
      if (row.typeCode === '5' || row.typeCode === null) {
        console.log('aaa')
        const that = this
        var xhr = new XMLHttpRequest()
        xhr.open('GET', row.pictureUrl, true)
        xhr.responseType = 'arraybuffer'
        xhr.onload = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            that.btnTitle = '下载'
            that.isLoading = false
            const blob = this.response
            // 转换一个blob链接
            const u = window.URL.createObjectURL(new Blob([blob], { type: 'video/mp4' }))
            const a = document.createElement('a')
            a.download = `${that.carNumAndTime} ${row.title}`
            a.href = u
            a.style.display = 'none'
            document.body.appendChild(a)
            a.click()
            a.remove()
            setTimeout(() => {
              loading.close()
            }, 2000)
          } else {
            that.$message.warning('正在合成视频请稍后再尝试')
            setTimeout(() => {
              loading.close()
            }, 2000)
          }
        }
        xhr.send()
      } else if (row.typeCode !== null) {
        try {
          const image = new Image()
          image.setAttribute('crossOrigin', 'anonymous')
          image.onload = () => {
            const canvas = document.createElement('canvas')
            canvas.width = image.width
            canvas.height = image.height
            const context = canvas.getContext('2d')
            context.drawImage(image, 0, 0, image.width, image.height)
            const url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
            const a = document.createElement('a') // 生成一个a元素
            const event = new MouseEvent('click') // 创建一个单击事件
            a.download = `${this.carNumAndTime} ${row.title}` // 设置图片名称
            a.href = url // 将生成的URL设置为a.href属性
            a.dispatchEvent(event) // 触发a的单击事件
            setTimeout(() => {
              loading.close()
            }, 2000)
          }
          image.src = row.pictureUrl
        } catch (err) {
          console.log(err)
          this.$message.error('下载图片失败')
          setTimeout(() => {
            loading.close()
          }, 2000)
        }
      }
    },
    // 表格选择项变化时触发
    selectionChange(selection) {
      this.selectData = selection
    },
    // 下载选中的资源
    downLoadSelectSource() {
      if (this.selectData.length === 1) {
        this.donwLoadItem(this.selectData[0])
      } else if (this.selectData.length === 0) {
        this.$message.warning('请选择需要下载的资源')
      } else if (this.selectData.length > 1) {
        const loading = this.$loading({
          lock: true,
          text: '正在打包下载',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const blogTitle = `${this.carNumAndTime} 压缩包`
        const zip = new JSZip()
        const promises = []
        const cache = {}
        // 要下载文件的url
        const arrImg = []
        console.log(this.selectData)
        // fileList问下载的文件的全连接地址集合
        for (let i = 0; i < this.selectData.length; i++) {
          arrImg.push({
            path: this.selectData[i].pictureUrl,
            name: this.selectData[i].title,
            // 获取文件后缀名
            suffix: this.selectData[i].pictureUrl.substring(
              this.selectData[i].pictureUrl.lastIndexOf('.')
            )
          })
        }
        console.log(arrImg)

        for (const item of arrImg) {
          const promise = this.getSourceArrayBuffer(item.path).then((data) => {
            // 下载文件, 并存成ArrayBuffer对象(blob)
            zip.file(item.name + item.suffix, data, { binary: true }) // 逐个添加文件
            cache[item.name] = data
          })
          promises.push(promise)
        }

        Promise.all(promises)
          .then(() => {
            zip.generateAsync({ type: 'blob' }).then((content) => {
              // 生成二进制流
              FileSaver.saveAs(content, blogTitle) // 利用file-saver保存文件  自定义文件名
              this.btnLoading = false
            })
            setTimeout(() => {
              loading.close()
            }, 2000)
          })
          .catch(() => {
            this.$message.error('文件压缩失败，请稍后再试')
            setTimeout(() => {
              loading.close()
            }, 2000)
          })
      }
    },
    getSourceArrayBuffer(url) {
      // url为文件地址
      return new Promise((resolve, reject) => {
        // 通过请求获取文件blob格式
        const xmlhttp = new XMLHttpRequest()
        xmlhttp.open('GET', url, true)
        xmlhttp.responseType = 'arraybuffer'
        xmlhttp.onload = function () {
          if (this.status === 200) {
            resolve(this.response)
          } else {
            reject(this.status)
          }
        }
        xmlhttp.send()
      })
    },
    getType(type) {
      if (type === null) {
        return '视频'
      } else if (type === '0') {
        return '车牌图片'
      } else if (type === '1') {
        return '过车图片'
      }
    }
  }
}
</script>

<style scoped></style>
